<?php

namespace app\index\controller;

use tian\Config;
use tian\Session;
use tian\Redis;

class Duel extends Base
{
    public function pve()
    {
        try {
            $redis = Redis::getInstance(config('redis')['default']);
            $role_id = Session::get('uid');

            $str = input('str');
            $this->assign('str', $str);

            $duel_id = $this->strAnalysis($str, $role_id);

            $infoMonster = model('MapMonster')->getInfo($duel_id);
            $this->assign('infoMonster', $infoMonster);

            $infoRole = model('Role')->getRoleAttribute($role_id);
            if (!empty($infoRole)) {
                $infoRole['yp1_name'] = '';
                if ($infoRole['yp1'] != 0) {
                    $infoRole['yp1_name'] = model('RoleDrug')->findValue(['id' => $infoRole['yp1']], 'ypname');
                }
                $infoRole['yp2_name'] = '';
                if ($infoRole['yp2'] != 0) {
                    $infoRole['yp2_name'] = model('RoleDrug')->findValue(['id' => $infoRole['yp2']], 'ypname');
                }
                $infoRole['yp3_name'] = '';
                if ($infoRole['yp3'] != 0) {
                    $infoRole['yp3_name'] = model('RoleDrug')->findValue(['id' => $infoRole['yp3']], 'ypname');
                }
            }
            $this->assign('infoRole', $infoRole);

            $list = [];
            $listRedis = $redis->lRange($str, 0, 20);
            if (!empty($listRedis)) {
                $key = 0;
                foreach ($listRedis as $val) {
                    $list[$key] = $val;
                    $key++;
                }
            }
            $list = array_reverse($list);
            $this->assign('list', $list);

            $this->fetch('pve');
        } catch (\Throwable $e) {
            echo $e->getMessage();
        }
    }

    public function battle()
    {
        try {
            $type = input('type');
            $str = input('str');
            $time = time();

            $role_id = Session::get('uid');
            $infoRole = model('Role')->getRoleAttribute($role_id);
            if (empty($infoRole)) {
                returnJson(0, '数据错误');
            }
            if ($infoRole['uhp'] <= 0) {
                returnJson(0, '你已身受重伤');
            }

            $duel_id = $this->strAnalysis($str, $role_id);
            $infoMonster = model('MapMonster')->getInfo($duel_id);
            if($time < ($infoMonster['addtime'] + 1 * 60)){
                returnJson(0, '怪物刚刷新，1分钟后可击杀');
            }

            //更新归属
            $tempBoss = [
                'id' => $duel_id,
                'sid' => $role_id,
                'havetime' => $time,
            ];
            model('MapMonster')->saved($tempBoss);

            $redis = Redis::getInstance(config('redis')['default']);

            if ($type == 'attack') {//普攻
                $role_temp = [
                    'uid' => $role_id
                ];
                $foe_temp = [
                    'id' => $duel_id
                ];

                //speed 变数计算
                $role_speed = $infoRole['usd'];
                $foe_speed = $infoMonster['gsd'];
                //增加变数 sd 补偿值
                $diff = get_speed_compensate($role_speed, $foe_speed);
                if ($role_speed > $foe_speed) {
                    $foe_speed = $foe_speed + $diff;
                } else {
                    $role_speed = $role_speed + $diff;
                }

                //hurt count 可造成的(伤害 + 暴击)
                $role_hurt = $infoRole['ugj'] + burst($infoRole['ugj'], $infoRole['ubj']);
                $foe_hurt = $infoMonster['ggj'] + burst($infoMonster['ggj'], $infoMonster['gbj']);

                //承受结果伤害
                $role_hurt_final = ($infoRole['ufy'] >= $foe_hurt) ? 1 : ($foe_hurt - $infoRole['ufy']);
                $foe_hurt_final = ($infoMonster['gfy'] >= $role_hurt) ? 1 : ($role_hurt - $infoMonster['gfy']);

                //hp count 生命
                $role_hp = $infoRole['uhp'] - $role_hurt_final;
                $foe_hp = $infoMonster['ghp'] - $foe_hurt_final;

                //行动计算 + 吸血
                $role_temp['uhp'] = $role_hp + $infoRole['uxx'];
                $foe_temp['ghp'] = $foe_hp + $infoMonster['gxx'];
                //role 先手
                if ($role_speed >= $foe_speed) {
                    $redis->lPush($str, date('H:i:s') . '你对[' . $infoMonster['gname'] . ']造成 ' . $foe_hurt_final . '伤害。');
                    if ($foe_hp <= 0) {
                        //foe die
                        $role_temp['uhp'] = $infoRole['uhp'] + $infoRole['uxx'];
                        $foe_temp['ghp'] = 0;

                        $redis->lPush($str, date('H:i:s') . '[' . $infoMonster['gname'] . '] 死亡');
                    } else {
                        $redis->lPush($str, date('H:i:s') . '[' . $infoMonster['gname'] . ']对你造成 ' . $role_hurt_final . '伤害。');
                    }
                } else {
                    //foe 先手
                    $redis->lPush($str, date('H:i:s') . '[' . $infoMonster['gname'] . ']对你造成 ' . $role_hurt_final . '伤害。');
                    if ($role_hp <= 0) {
                        //role die
                        $role_temp['uhp'] = 0;
                        $foe_temp['ghp'] = $infoMonster['ghp'] + $infoMonster['gxx'];

                        $redis->lPush($str, date('H:i:s') . '你已身受重伤。');
                    } else {
                        $redis->lPush($str, date('H:i:s') . '你对[' . $infoMonster['gname'] . ']造成 ' . $foe_hurt_final . '伤害。');
                    }
                }

                //数据更新
                if ($role_temp['uhp'] > $infoRole['umaxhp']) {
                    $role_temp['uhp'] = $infoRole['umaxhp'];
                }
                model('Role')->saved($role_temp);
                model('MapMonster')->saved($foe_temp);

                if ($role_temp['uhp'] == 0) {
                    returnJson(0, '你已身受重伤');
                }
                if ($foe_temp['ghp'] == 0) {
                    $redis->del($str);

                    //计算奖励修为和灵石
                    $markUp = 0;    //跨级爆率加成
                    $exp = ceil($infoMonster['gexp']);
                    $yxb = round($infoMonster['glv'] / 2.9) + 1;
                    $lv = abs($infoRole['ulv'] - $infoMonster['glv']);
                    if ($infoRole['ulv'] > $infoMonster['glv'] && $lv > 10) {
                        $yxb = 0;
                        $exp = 0;
                    }
                    if ($infoRole['ulv'] < $infoMonster['glv']) {//正向跨级
                        if($lv >= 10){
                            $exp = $exp + round(($exp * $lv)/50);
                            $yxb = $yxb + $lv * 2;
                            $markUp = 15;
                        }else{
                            $exp = $exp + round(($exp * $lv)/100);
                            $yxb = $yxb + $lv;
                            $markUp = $lv;
                        }
                    }

                    $roleTemp = [
                        'uid' => $role_id,
                        'uexp' => $infoRole['uexp'] + $exp,
                        'uyxb' => $infoRole['uyxb'] + $yxb,
                    ];
                    model('Role')->saved($roleTemp);

                    model('MapMonster')->del($duel_id);

                    //根据掉落几率奖励装备道具药品
                    $title = '';
                    $monsterInfo = model('Monster')->getInfo($infoMonster['gyid']);
                    $resZb = $this->strSelect($monsterInfo['gzb'], ($monsterInfo['dljv'] + $markUp), 1);
                    if ($resZb != '') $title .= $resZb;
                    $resDj = $this->strSelect($monsterInfo['gdj'], ($monsterInfo['djjv'] + $markUp), 2);
                    if ($resDj != '') $title .= $resDj;
                    $resYp = $this->strSelect($monsterInfo['gyp'], ($monsterInfo['ypjv'] + $markUp), 3);
                    if ($resYp != '') $title .= $resYp;

                    //验证是否是任务需求怪物
                    $this->setRoleTask($role_id, 2, $infoMonster['gyid'], 1);

                    returnJson(2, '奖励修为：' . $infoMonster['gexp'] . ' 灵石：' . $yxb . $title, ['url' => url('home/index')]);
                }
            }
            if ($type == 'sorcery') {//用技能

            }
            if ($type == 'drug') {//嗑药
                $target_id = input('target_id');
                $infoRoleDrug = model('RoleDrug')->getInfo($target_id);
                if (empty($infoRoleDrug) || $infoRoleDrug['uid'] != $role_id) {
                    returnJson(0, '非法操作');
                }

                if ($infoRoleDrug['type'] == 1) {
                    $uhp = $infoRole['uhp'] + $infoRoleDrug['yphp'];
                    $ump = $infoRole['ump'] + $infoRoleDrug['ypmana'];
                    if ($uhp > $infoRole['umaxhp']) $uhp = $infoRole['umaxhp'];
                    if ($ump > $infoRole['umaxmp']) $ump = $infoRole['umaxmp'];

                    $temp = [
                        'uid' => $role_id,
                        'uhp' => $uhp,
                        'ump' => $ump,
                    ];
                    model('Role')->saved($temp);
                }
                if ($infoRoleDrug['type'] == 2) {
                    $uexp = $infoRole['uexp'] + $infoRoleDrug['exp'];

                    $temp = [
                        'uid' => $role_id,
                        'uexp' => $uexp,
                    ];
                    model('Role')->saved($temp);
                }
                if ($infoRoleDrug['type'] == 3) {
                    returnJson(0, '增益类正在加紧开发中');
                }

                //减少数量
                if ($infoRoleDrug['ypsum'] == 1) {
                    model('RoleDrug')->del($target_id);
                    $tempRole = ['uid' => $role_id];
                    if ($target_id == $infoRole['yp1']) $tempRole['yp1'] = 0;
                    if ($target_id == $infoRole['yp2']) $tempRole['yp2'] = 0;
                    if ($target_id == $infoRole['yp3']) $tempRole['yp3'] = 0;
                    model('Role')->saved($tempRole);
                } else {
                    $tempRoleDrug = [
                        'id' => $target_id,
                        'ypsum' => $infoRoleDrug['ypsum'] - 1,
                    ];
                    model('RoleDrug')->saved($tempRoleDrug);
                }
            }

            returnJson(1, '请继续');
        } catch (\Throwable $e) {
            echo $e->getMessage();
        }
    }

    private function strSelect($strIds, $jv, $type)
    {
        try {
            $strIds = ($strIds != '' && $strIds != null) ? $strIds : '';
            $role_id = Session::get('uid');
            $bv = mt_rand(1, 100);
            //setLog('爆率：' . $bv);
            //setLog('掉落率：' . $jv);
            //setLog('strIds：' . $strIds);

            $title = '';
            if ($type == 1) {
                if ($jv >= $bv && $strIds != '') {
                    $list = model('Equip')->getList([['zbid', 'in', $strIds]]);
                    if (!$list->isEmpty()) {
                        $num = mt_rand(0, count($list) - 1);
                        $id = $list[$num]['zbid'];
                        $name = $list[$num]['zbname'];

                        //setLog('掉落装备：' . $name);
                        model('RoleEquip')->addzb($role_id, $id);

                        $title .= " 获得:" . $name;
                    }
                }
            }
            if ($type == 2) {
                if ($jv >= $bv && $strIds != '') {
                    $list = model('Prop')->getList([['djid', 'in', $strIds]]);
                    if (!$list->isEmpty()) {
                        $num = mt_rand(0, count($list) - 1);
                        $id = $list[$num]['djid'];
                        $name = $list[$num]['djname'];
                        $sum = mt_rand(1, 3);

                        //setLog('掉落道具：' . $name);
                        model('RoleProp')->adddj($role_id, $id, $sum);

                        //验证是否是任务需求道具
                        $this->setRoleTask($role_id, 1, $id, $sum);

                        $title .= " 获得:" . $name;
                    }
                }
            }
            if ($type == 3) {
                if ($jv >= $bv && $strIds != '') {
                    $list = model('Drug')->getList([['ypid', 'in', $strIds]]);
                    if (!$list->isEmpty()) {
                        $num = mt_rand(0, count($list) - 1);
                        $id = $list[$num]['ypid'];
                        $name = $list[$num]['ypname'];
                        $sum = mt_rand(1, 3);

                        //setLog('掉落药品：' . $name);
                        model('RoleDrug')->addyp($role_id, $id, $sum);

                        $title .= " 获得:" . $name . 'x' . $sum;
                    }
                }
            }

            return $title;
        } catch (\Throwable $e) {
            setLog($e->getMessage());
            echo $e->getMessage();
        }
    }

    private function setRoleTask($role_id, $rwzl, $target_id, $num = 1)
    {
        try {
            $whereTask = [];
            $whereTask[] = ['uid', '=', $role_id];
            $whereTask[] = ['rwzt', '<>', 3];    //未完成
            $whereTask[] = ['rwzl', '=', $rwzl];    //1道具收集,2打怪
            $whereTask[] = ['rwyq', '=', $target_id];

            $listRoleTask = model('RoleTask')->getList($whereTask);
            if (!empty($listRoleTask)) {
                foreach ($listRoleTask as $k => $vo) {
                    $tempTask = [
                        'id' => $vo['id'],
                        'rwnowcount' => $vo['rwnowcount'] + $num,
                    ];
                    model('RoleTask')->saved($tempTask);
                }
            }
        } catch (\Throwable $e) {
            setLog($e->getMessage());
            echo $e->getMessage();
        }
    }

}
